package com.itzxx.library_base_ktx.utils

import android.R.attr.radius
import android.graphics.Bitmap
import android.graphics.BitmapShader
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.RectF
import android.graphics.Shader
import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation
import java.security.MessageDigest


class TopCornersRoundedTransformation(radius: Int) : BitmapTransformation() {

    private var mRadius: Int = radius


    override fun updateDiskCacheKey(messageDigest: MessageDigest) {
        messageDigest.update(("top_corners_rounded" + mRadius).toByte());
    }

    override fun transform(
        pool: BitmapPool,
        toTransform: Bitmap,
        outWidth: Int,
        outHeight: Int
    ): Bitmap? {
        return topRoundedCorners(pool, toTransform)
    }

    private fun topRoundedCorners(pool: BitmapPool, source: Bitmap?): Bitmap? {
        if (source == null) return null


        val result = pool[source.width, source.height, Bitmap.Config.ARGB_8888]
        result.setHasAlpha(true)


        val canvas = Canvas(result)
        val paint = Paint()
        paint.isAntiAlias = true
        paint.setShader(BitmapShader(source, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP))


        // 绘制圆角矩形（只对左上和右上角应用圆角）
        val rectF = RectF(0f, 0f, source.width.toFloat(), source.height.toFloat())
        canvas.drawRoundRect(rectF, radius.toFloat(), radius.toFloat(), paint)


        // 绘制矩形以覆盖底部两个角
        val bottomRect =
            RectF(0f, radius.toFloat(), source.width.toFloat(), source.height.toFloat())
        canvas.drawRect(bottomRect, paint)


        return result
    }


}